package com.cw.jeeyt.core.impl;

import org.apache.rocketmq.client.producer.SendStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.cw.jeeyt.common.enums.EnumCommonError;
import com.cw.jeeyt.core.intf.TimeoutProcessCore;
import com.cw.lang.common.exception.BizException;
import com.cw.mq.Producer;
import com.cw.mq.SendResult;
import com.google.gson.Gson;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class TimeoutProcessCoreImpl implements TimeoutProcessCore {
    @Value("${loan.check.maxTime:3}")
    private final int queryTimes = 3;
    @Autowired
    @Qualifier("commonProducer")
    private Producer commonProducer;
    /**
     * 重发mq
     *
     * @param mqRequestBo
     * @param topic
     * @param tag
     */
    @Override
    public void retryProducer(Object mqRequestBo, String topic, String tag) {
        log.info("开始发起重试添加MQ事件, topic:{}, tag:{}, 参数:{}", topic, tag, new Gson().toJson(mqRequestBo));
        SendResult result = null;
        for (int i = 0; i < queryTimes; i++) {
            try {
                result = commonProducer.send(topic, tag, topic + "|" + tag, mqRequestBo);
                //获取查证结果失败
                if (!SendStatus.SEND_OK.equals(result.getSendStatus())) {
                    log.warn("添加mq事件失败,请求参数为:{},第{}次添加失败:", new Gson().toJson(mqRequestBo), i + 1);
                    continue;
                }
                log.info("添加mq事件任务成功。交易参数为：{}", new Gson().toJson(mqRequestBo));
                return;
            } catch (Exception e) {
                log.error("添加mq事件任务失败{},第{}次添加失败", new Gson().toJson(mqRequestBo));
            }
        }
        log.error("添加mq事件任务:交易失败.交易参数：{}", new Gson().toJson(mqRequestBo));
        /**添加异步任务异常抛出*/
        throw new BizException(EnumCommonError.MQ_RESEND_ERROR.getCode(),
            EnumCommonError.MQ_RESEND_ERROR.getDescription(), this.getClass());
    }
}
